package cn.soboys.subsys.listener;

import cn.soboys.subsys.bean.insurbs.DeptBs;
import cn.soboys.subsys.bean.insurbs.UserBs;
import cn.soboys.subsys.bean.jeecg.SysDepart;
import cn.soboys.subsys.bean.jeecg.SysUser;
import cn.soboys.subsys.bean.jeecg.SysUserDepart;
import cn.soboys.subsys.bean.yxinsur.OrgYx;
import cn.soboys.subsys.bean.yxinsur.UserYx;
import cn.soboys.subsys.bean.zj.SysEmployee;
import cn.soboys.subsys.bean.zj.Sysorganize;
import cn.soboys.subsys.bean.zj.Sysuser;
import cn.soboys.subsys.mapper.insurbs.DeptBsMapper;
import cn.soboys.subsys.mapper.insurbs.UserBsMapper;
import cn.soboys.subsys.mapper.jeecg.SysDepartMapper;
import cn.soboys.subsys.mapper.jeecg.SysUserDepartMapper;
import cn.soboys.subsys.mapper.jeecg.SysUserMapper;
import cn.soboys.subsys.mapper.yxinsur.OrgYxMapper;
import cn.soboys.subsys.mapper.yxinsur.UserYxMapper;
import cn.soboys.subsys.mapper.zj.SysEmployeeMapper;
import cn.soboys.subsys.mapper.zj.SysorganizeMapper;
import cn.soboys.subsys.mapper.zj.SysuserMapper;
import cn.soboys.subsys.utils.JsonUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
public class MyKafkaListener {
    SysUserMapper sysUserMapper;
    SysDepartMapper sysDepartMapper;
    SysUserDepartMapper sysUserDepartMapper;

    SysuserMapper zjuserMapper;
    SysEmployeeMapper zjEmployeeMapper;
    SysorganizeMapper zjOrganizeMapper;

    UserBsMapper userBsMapper;
    DeptBsMapper deptBsMapper;

    UserYxMapper userYxMapper;
    OrgYxMapper orgYxMapper;

    public MyKafkaListener(SysUserMapper sysUserMapper,
                           SysDepartMapper sysDepartMapper,
                           SysUserDepartMapper sysUserDepartMapper,
                           SysuserMapper sysuserMapper,
                           SysEmployeeMapper sysEmployeeMapper,
                           SysorganizeMapper sysorganizeMapper,
                           UserBsMapper userBsMapper,
                           DeptBsMapper deptBsMapper,
                           UserYxMapper userYxMapper,
                           OrgYxMapper orgYxMapper){
        this.sysUserMapper = sysUserMapper;
        this.sysDepartMapper = sysDepartMapper;
        this.sysUserDepartMapper = sysUserDepartMapper;
        this.zjuserMapper = sysuserMapper;
        this.zjEmployeeMapper = sysEmployeeMapper;
        this.zjOrganizeMapper = sysorganizeMapper;
        this.userBsMapper = userBsMapper;
        this.deptBsMapper = deptBsMapper;
        this.userYxMapper = userYxMapper;
        this.orgYxMapper = orgYxMapper;
    }

    @KafkaListener(id = "subsys_zj",//id是消费者监听容器
            topics={"keycloak_adminevent"})
    public void listen(ConsumerRecord<?, ?> record) {
        try {
            System.out.println("topic:" + record.topic());
            System.out.println("key:" + record.key());
            System.out.println("value:" + record.value());
            log.info(record.value().toString());
            String val = (String) record.value();
            Map valMap = JsonUtil.stringToObject(val, Map.class);
            String resourceType = (String)valMap.get("resourceType");
            String operationType = (String)valMap.get("operationType");
            Map repMap = JsonUtil.stringToObject("" +valMap.get("representation"),Map.class);
            if("USER".equals(resourceType)){
                jeecgUserOper(valMap,repMap,operationType);
                zjUserOper(valMap,repMap,operationType);
                insurbsUserOper(valMap,repMap,operationType);
                insuryxUserOper(valMap,repMap,operationType);
            }
            if("GROUP_MEMBERSHIP".equals(resourceType)){
                jeecgGMOper(valMap,repMap,operationType);
                zjGMOper(valMap,repMap,operationType);
                insurbsGMOper(valMap,repMap,operationType);
                insuryxGMOper(valMap,repMap,operationType);
            }
            if("GROUP".equals(resourceType)){
                jeecgGroupOper(valMap,repMap,operationType);
                zjGroupOper(valMap,repMap,operationType);
                insurbsGroupOper(valMap,repMap,operationType);
                insuryxGroupOper(valMap,repMap,operationType);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    private void jeecgGroupOper(Map valMap, Map repMap, String operationType) {
        if("CREATE".equals(operationType)) {
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String pid = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            SysDepart pdept = sysDepartMapper.selectOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getKeycloakId,pid));
            String pcode = null == pdept? "":pdept.getId();
            SysDepart depart = new SysDepart();
            depart.setDepartName(name);
            depart.setKeycloakId(id);
            depart.setParentId(pcode);
            depart.setDelFlag(""+0);
            sysDepartMapper.insert(depart);
        }else if("UPDATE".equals(operationType)){
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String code = "" +((List)((Map)repMap.get("attributes")).get("code")).get(0);
            SysDepart depart = sysDepartMapper.selectOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getKeycloakId,id));
            depart.setOrgCode(code);
            depart.setDepartName(name);
            sysDepartMapper.updateById(depart);
        }else if("DELETE".equals(operationType)){
            String id = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            sysDepartMapper.delete(new LambdaUpdateWrapper<SysDepart>().eq(SysDepart::getKeycloakId,id));
        }
    }

    private void zjGroupOper(Map valMap, Map repMap, String operationType) {
        if("CREATE".equals(operationType)) {
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String pid = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            Sysorganize pdept = zjOrganizeMapper.selectOne(new LambdaQueryWrapper<Sysorganize>().eq(Sysorganize::getKeycloakId,pid));
            String pcode = null == pdept? "":pdept.getOrgCode();
            String pname = null == pdept? "":pdept.getOrgName();
            Sysorganize depart = new Sysorganize();
            depart.setOrgName(name);
            depart.setKeycloakId(id);
            depart.setUpperOrgCode(pcode);
            depart.setUpperOrgName(pname);
            zjOrganizeMapper.insert(depart);
        }else if("UPDATE".equals(operationType)){
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String code = "" +((List)((Map)repMap.get("attributes")).get("code")).get(0);
            String type = "" + ((List)((Map)repMap.get("attributes")).get("type")).get(0);
            Sysorganize depart = zjOrganizeMapper.selectOne(new LambdaQueryWrapper<Sysorganize>().eq(Sysorganize::getKeycloakId,id));
            depart.setOrgCode(code);
            depart.setOrgName(name);
            depart.setOrgTypeCode(StringUtils.equals("company",type)?"org":"dept");
            zjOrganizeMapper.updateById(depart);
        }else if("DELETE".equals(operationType)){
            String id = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            zjOrganizeMapper.delete(new LambdaUpdateWrapper<Sysorganize>().eq(Sysorganize::getKeycloakId,id));
        }
    }

    private void insurbsGroupOper(Map valMap, Map repMap, String operationType) {
        if("CREATE".equals(operationType)) {
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String pid = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            DeptBs pdept = deptBsMapper.selectOne(new LambdaQueryWrapper<DeptBs>().eq(DeptBs::getKeycloakId,pid));
            Long pcode = null == pdept? 0:pdept.getDeptId();
            DeptBs depart = new DeptBs();
            depart.setName(name);
            depart.setKeycloakId(id);
            depart.setParentId(pcode);
            depart.setDelFlag(0);
            deptBsMapper.insert(depart);
        }else if("UPDATE".equals(operationType)){
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

//            String code = "" +((List)((Map)repMap.get("attributes")).get("code")).get(0);
//            String type = "" + ((List)((Map)repMap.get("attributes")).get("type")).get(0);
            DeptBs depart = deptBsMapper.selectOne(new LambdaQueryWrapper<DeptBs>().eq(DeptBs::getKeycloakId,id));
            depart.setName(name);
            deptBsMapper.updateById(depart);
        }else if("DELETE".equals(operationType)){
            String id = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            deptBsMapper.delete(new LambdaUpdateWrapper<DeptBs>().eq(DeptBs::getKeycloakId,id));
        }
    }

    private void insuryxGroupOper(Map valMap, Map repMap, String operationType) {
        if("CREATE".equals(operationType)) {
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String pid = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            OrgYx pdept = orgYxMapper.selectOne(new LambdaQueryWrapper<OrgYx>().eq(OrgYx::getKeycloakId,pid));
            String pcode = null == pdept? "":pdept.getParentOrgCode();
            OrgYx depart = new OrgYx();
            depart.setOrgName(name);
            depart.setKeycloakId(id);
            depart.setParentOrgCode(pcode);
            depart.setStatus("N");
            depart.setOrgType("org");
            depart.setCreateTime(new Date());
            depart.setCreator("1");
            depart.setLastModifyTime(new Date());
            depart.setLastModifyPerson("1");
            orgYxMapper.insert(depart);
        }else if("UPDATE".equals(operationType)){
            String id = "" + repMap.get("id");
            String name = "" + repMap.get("name");

            String code = "" +((List)((Map)repMap.get("attributes")).get("code")).get(0);
//            String type = "" + ((List)((Map)repMap.get("attributes")).get("type")).get(0);
            OrgYx depart = orgYxMapper.selectOne(new LambdaQueryWrapper<OrgYx>().eq(OrgYx::getKeycloakId,id));
            depart.setOrgName(name);
            depart.setOrgCode(code);
            orgYxMapper.updateById(depart);
        }else if("DELETE".equals(operationType)){
            String id = StringUtils.split("" + valMap.get("resourcePath"),"/")[1];
            orgYxMapper.delete(new LambdaUpdateWrapper<OrgYx>().eq(OrgYx::getKeycloakId,id));
        }
    }

    private void jeecgGMOper(Map valMap, Map repMap, String operationType) throws Exception{
        String path = (String)valMap.get("resourcePath");
        String[] ids = path.split("/");
        String userid = ids[1];
        String orgid = ids[3];
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getKeycloakId,userid));
        SysDepart depart = sysDepartMapper.selectOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getKeycloakId,orgid));
        if(null == user || null == depart){
            throw new Exception("用户或组织为空");
        }
        SysUserDepart userDepart = new SysUserDepart();
        userDepart.setUserId(user.getId());
        userDepart.setDepId(depart.getId());
        if("CREATE".equals(operationType)) {
            sysUserDepartMapper.insert(userDepart);
        }else if("DELETE".equals(operationType)){
            sysUserDepartMapper.delete(new LambdaUpdateWrapper<SysUserDepart>().eq(SysUserDepart::getUserId,userDepart.getUserId()).eq(SysUserDepart::getDepId,userDepart.getDepId()));
        }
    }


    private void zjGMOper(Map valMap, Map repMap, String operationType) throws Exception{
        String path = (String)valMap.get("resourcePath");
        String[] ids = path.split("/");
        String userid = ids[1];
        String orgid = ids[3];
        SysEmployee employee = zjEmployeeMapper.selectOne(new LambdaQueryWrapper<SysEmployee>().eq(SysEmployee::getKeycloakId,userid));
        Sysorganize depart = zjOrganizeMapper.selectOne(new LambdaQueryWrapper<Sysorganize>().eq(Sysorganize::getKeycloakId,orgid));
        if(null == employee || null == depart){
            throw new Exception("用户或组织为空");
        }
//        SysUserDepart userDepart = new SysUserDepart();
//        userDepart.setUserId(user.getId());
//        userDepart.setDepId(depart.getId());
        if("CREATE".equals(operationType)) {
            Sysorganize pdept = depart;

            while (pdept != null && !StringUtils.equals("org",pdept.getOrgTypeCode()) ) {
                pdept = zjOrganizeMapper.selectOne(new LambdaUpdateWrapper<Sysorganize>().eq(Sysorganize::getOrgCode, pdept.getUpperOrgCode()));
            }
            String pcode = pdept == null?"":pdept.getOrgCode();
            String pname = pdept == null?"":pdept.getOrgName();
            employee.setDeptId(depart.getOrgCode()).setDeptName(depart.getOrgName()).setOrgId(pcode).setOrgName(pname);
            zjEmployeeMapper.updateById(employee);
        }
//        else if("DELETE".equals(operationType)){
//            sysUserDepartMapper.delete(new LambdaUpdateWrapper<SysUserDepart>().eq(SysUserDepart::getUserId,userDepart.getUserId()).eq(SysUserDepart::getDepId,userDepart.getDepId()));
//        }
    }

    private void insurbsGMOper(Map valMap, Map repMap, String operationType) throws Exception{
        String path = (String)valMap.get("resourcePath");
        String[] ids = path.split("/");
        String userid = ids[1];
        String orgid = ids[3];
        UserBs user = userBsMapper.selectOne(new LambdaQueryWrapper<UserBs>().eq(UserBs::getKeycloakId,userid));
        DeptBs depart = deptBsMapper.selectOne(new LambdaQueryWrapper<DeptBs>().eq(DeptBs::getKeycloakId,orgid));
        if(null == user || null == depart){
            throw new Exception("用户或组织为空");
        }

        if("CREATE".equals(operationType)) {
            user.setDept(depart.getDeptId());
            userBsMapper.updateById(user);
        }
//        else if("DELETE".equals(operationType)){
//            sysUserDepartMapper.delete(new LambdaUpdateWrapper<SysUserDepart>().eq(SysUserDepart::getUserId,userDepart.getUserId()).eq(SysUserDepart::getDepId,userDepart.getDepId()));
//        }
    }

    private void insuryxGMOper(Map valMap, Map repMap, String operationType) throws Exception{
        String path = (String)valMap.get("resourcePath");
        String[] ids = path.split("/");
        String userid = ids[1];
        String orgid = ids[3];
        UserYx user = userYxMapper.selectOne(new LambdaQueryWrapper<UserYx>().eq(UserYx::getKeycloakId,userid));
        OrgYx depart = orgYxMapper.selectOne(new LambdaQueryWrapper<OrgYx>().eq(OrgYx::getKeycloakId,orgid));
        if(null == user || null == depart){
            throw new Exception("用户或组织为空");
        }

        if("CREATE".equals(operationType)) {
            user.setOrgId(depart.getId());
            userYxMapper.updateById(user);
        }
//        else if("DELETE".equals(operationType)){
//            sysUserDepartMapper.delete(new LambdaUpdateWrapper<SysUserDepart>().eq(SysUserDepart::getUserId,userDepart.getUserId()).eq(SysUserDepart::getDepId,userDepart.getDepId()));
//        }
    }

    private void jeecgUserOper(Map valMap,Map repMap,String operationType) {
        SysUser user = new SysUser();
        user.setKeycloakId("" + StringUtils.replace("" + valMap.get("resourcePath"),"users/",""));
        if(null != repMap) {
            user.setUsername("" + repMap.get("username"));
            user.setRealname("" + repMap.get("firstName"));
        }
        if("UPDATE".equals(operationType)){
            sysUserMapper.update(user,new LambdaUpdateWrapper<SysUser>().eq(SysUser::getKeycloakId,"" + user.getKeycloakId()));
        }else if("CREATE".equals(operationType)){
            user.setDelFlag(0);
            sysUserMapper.insert(user);
        }else if("DELETE".equals(operationType)){
            sysUserMapper.delete(new LambdaUpdateWrapper<SysUser>().eq(SysUser::getKeycloakId,user.getKeycloakId()));
        }

    }

    private void zjUserOper(Map valMap,Map repMap,String operationType) {
        Sysuser user = new Sysuser();
        SysEmployee employee = new SysEmployee();
        user.setKeycloakId("" + StringUtils.replace("" + valMap.get("resourcePath"),"users/",""));
        employee.setKeycloakId(user.getKeycloakId());
        if(null != repMap) {
            user.setLoginCode("" + repMap.get("username"));
            user.setLoginName("" + repMap.get("firstName"));
            employee.setBizFlag("1")
                    .setEmployeeStutas("onjob")
                    .setIsUserFlag("1")
                    .setUserCode(user.getLoginCode())
                    .setUserName(user.getLoginName());
        }
        if("UPDATE".equals(operationType)){
            zjEmployeeMapper.update(employee,new LambdaUpdateWrapper<SysEmployee>().eq(SysEmployee::getKeycloakId,"" + employee.getKeycloakId()));
            zjuserMapper.update(user,new LambdaUpdateWrapper<Sysuser>().eq(Sysuser::getKeycloakId,"" + user.getKeycloakId()));
        }else if("CREATE".equals(operationType)){
            user.setValidFlag(1);
            zjEmployeeMapper.insert(employee);
            user.setEmployeeID(employee.getId());
            zjuserMapper.insert(user);
        }else if("DELETE".equals(operationType)){
            zjEmployeeMapper.delete(new LambdaUpdateWrapper<SysEmployee>().eq(SysEmployee::getKeycloakId,employee.getKeycloakId()));
            zjuserMapper.delete(new LambdaUpdateWrapper<Sysuser>().eq(Sysuser::getKeycloakId,user.getKeycloakId()));
        }

    }

    private void insurbsUserOper(Map valMap,Map repMap,String operationType) {
        UserBs user = new UserBs();
        user.setKeycloakId("" + StringUtils.replace("" + valMap.get("resourcePath"),"users/",""));
        if(null != repMap) {
            user.setLoginName("" + repMap.get("username"));
            user.setNickName("" + repMap.get("firstName"));
        }
        if("UPDATE".equals(operationType)){
            userBsMapper.update(user,new LambdaUpdateWrapper<UserBs>().eq(UserBs::getKeycloakId,"" + user.getKeycloakId()));
        }else if("CREATE".equals(operationType)){
            userBsMapper.insert(user);
        }else if("DELETE".equals(operationType)){
            userBsMapper.delete(new LambdaUpdateWrapper<UserBs>().eq(UserBs::getKeycloakId,user.getKeycloakId()));
        }

    }

    private void insuryxUserOper(Map valMap,Map repMap,String operationType) {
        UserYx user = new UserYx();
        user.setKeycloakId("" + StringUtils.replace("" + valMap.get("resourcePath"),"users/",""));
        if(null != repMap) {
            user.setUsername("" + repMap.get("username"));
            user.setNickName("" + repMap.get("firstName"));
            user.setTrueName(user.getTrueName());
            user.setPassword("1");
            user.setState(0);
        }
        if("UPDATE".equals(operationType)){
            userYxMapper.update(user,new LambdaUpdateWrapper<UserYx>().eq(UserYx::getKeycloakId,"" + user.getKeycloakId()));
        }else if("CREATE".equals(operationType)){
            userYxMapper.insert(user);
        }else if("DELETE".equals(operationType)){
            userYxMapper.delete(new LambdaUpdateWrapper<UserYx>().eq(UserYx::getKeycloakId,user.getKeycloakId()));
        }

    }
}
